<template>
	<view>
		<uni-nav-bar :title="$t('personal.text10')" :fixed="true" :border="false" color="var(--theme-text-color)" backgroundColor="var(--theme-color)"></uni-nav-bar>
		<view class="icon-xl circle flex-center back-btn" style="position: fixed;top: 5px;left: 16px;z-index: 100;" @click="backPage">
			<uni-icons type="arrow-left" size="24" color="#fff"></uni-icons>
		</view>
		<view class="p-lr-16 mt20">
			<view class="" v-show="status == -1 || status == 2" style="padding-bottom: 50px;">
				<view class="text-align-center text-down" v-show="status == 2">
					{{$t('rzerrTips')}}
				</view>
				<uni-forms :modelValue="realInfo" ref="realRule" labelWidth="auto" label-position="top" :rules="rules">
					<uni-forms-item :label="$t('name')" name="name">
						<input class="u-input" v-model="realInfo.name" :placeholder="$t('enter')+$t('name')" />
					</uni-forms-item>
					<uni-forms-item :label="$t('personal.idCard')" name="idcrad">
						<input class="u-input" v-model="realInfo.idcrad" :placeholder="$t('enter')+$t('personal.idCard')" />
					</uni-forms-item>
					<uni-forms-item :label="$t('personal.nation')" name="nationality">
						<input class="u-input" v-model="realInfo.nationality":placeholder="$t('enter')+$t('personal.nation')" />
					</uni-forms-item>
					<view class="fs12 text-des-color">
						<text>{{$t('personal.uploadId')}}</text>
					</view>
					<view class="flex-between">
						<uni-forms-item name="brankImg">
							<view class="idcard-item" @click="chooseImage('brankImg')">
								<image v-show="!realInfo.brankImg" src="/static/personal/front.png" mode=""></image>
								<image v-show="realInfo.brankImg" :src="config.BASE_URL+realInfo.brankImg" mode=""></image>
								<text class="mt10 fs14 text-main-color">{{$t('idfimg')}}</text>
								<text class="mt5 fs12 text-des-color">{{$t('clickidfimg')}}</text>
							</view>
						</uni-forms-item>
						<uni-forms-item name="afterImg">
							<view class="idcard-item" @click="chooseImage('afterImg')">
								<image v-show="!realInfo.afterImg" src="/static/personal/front.png" mode=""></image>
								<image v-show="realInfo.afterImg" :src="config.BASE_URL+realInfo.afterImg" mode=""></image>
								<text class="mt10 fs14 text-main-color">{{$t('idaimg')}}</text>
								<text class="mt5 fs12 text-des-color">{{$t('clickidaimg')}}</text>
							</view>
						</uni-forms-item>
					</view>
					<button :class="['btn-submit', disabled?'login-btn-disabled':'login-btn']" :disabled="disabled" @click="submitForm">{{$t('submint')}}</button>
				</uni-forms>
			</view>
			<view class="flex-column" style="padding-top: 100px;" v-show="status==0">
				<image class="circle" src="../../../static/rzz.png" style="width: 98px; height: 98px;" mode=""></image>
				<text class="mt20 fb fs20">{{$t('rzz')}}</text>
				<text class="text-des-color mt10" style="font-size: 15px;">{{$t('rzshz')}}</text>
			</view>
			<view class="flex-column" style="padding-top: 100px;" v-show="status==1">
				<image class="circle" src="../../../static/rzcg.png" style="width: 98px; height: 98px;" mode=""></image>
				<text class="mt20 fb fs20">{{$t('rzzg')}}</text>
			</view>
		</view>
		<uni-popup ref="popup2" :style="{'z-index':1031}" type="center" backgroundColor="var(--theme-box-bg)">
			<view class="buyInfo fs14">
				<view class="" style="padding: 24px 24px 0 20px;">
					<view class="flex-column" style="justify-content: center;">
						<uni-icons type="checkbox" color="#25bc73" style="font-weight: bold;" size="36"></uni-icons>
						<text>{{$t('rzshz')}}</text>
					</view>
				</view>
				<view class="btn-group fs14 mt10">
					<view class="btn-b" @click="dialogConfirm">
						<text>{{$t('ikonw')}}</text>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import { onMounted, ref, watch } from 'vue';
	import { userRealAttest } from '../../../api/index.js'
	import config from '../../../config.js';
	import useGlobalProperties from '/utils/useGlobalProperties.js'
	const { $t,$i18n } = useGlobalProperties()
	const disabled = ref(true)
	const imageUrl = ref(null)
	const isRz = ref(false)
	const realInfo = ref({
		name:'',
		idcrad:'',
		nationality:'',
		brankImg:'',
		afterImg:'',
	})
	const rules = ref({
		name: { rules:[ { required: true, errorMessage: $t('enter')+$t('name'), },{
					validateFunction:function(rule,value,data,callback){
						const regex = /^[\u4e00-\u9fa5]+$/; // ^：开头；[a-zA-Z0-9]：允许的字符；*：0个或多个；$：结尾
						// console.log('regex.test(value)',regex.test(value));
						if (!regex.test(value)) {
							callback('只能输入中文')
						}
						return true
					}
				},]},
		idcrad: { rules:[ { required: true, errorMessage: $t('enter')+$t('idCard'), } ]},
		nationality: { rules:[ { required: true, errorMessage: $t('enter')+$t('nation'), } ]},
		brankImg: { rules:[ { required: true, errorMessage: $t('uploadp')+$t('idfimg'), } ]},
		afterImg: { rules:[ { required: true, errorMessage:$t('uploadp')+$t('idaimg'), } ]},
	})
	// 监听 loginForm 对象的变化
	watch(realInfo, (newVal, oldVal) => {
	  if(realInfo.value.name && realInfo.value.idcrad&& realInfo.value.nationality&& realInfo.value.brankImg&& realInfo.value.afterImg){
		  disabled.value = false
	  }else{
		  disabled.value = true
	  }
	}, { deep: true });  // 设置 deep 为 true 以便深度监听对象的变化
	// 选择图片
	const chooseImage = (type) =>{
		uni.chooseImage({
	        count: 1, // 限制只能选择一张图片
	        sizeType: ['original', 'compressed'], // 支持原图和压缩图
	        sourceType: ['album', 'camera'], // 支持从相册选择或拍照
	        success: (res) => {
	          const tempFilePaths = res.tempFilePaths; // 获取本地临时图片路径
	          // imageUrl.value = tempFilePaths[0]; // 预览图片
			  // console.log(imageUrl.value);
	          uploadImage(tempFilePaths[0],type); // 调用上传方法
	        },
	        fail: (err) => {
	          console.log('选择图片失败:', err);
	        },
		});
	}
	 // 上传图片
	const uploadImage = (filePath,type) => {
		uni.showLoading({
			title:'上传中...'
		})
		let header={};
		header["token"] = uni.getStorageSync('H5STOCK_USERINFO')? uni.getStorageSync('H5STOCK_USERINFO').token:''
		const uploadTask = uni.uploadFile({
		  url: config.BASE_URL+'/api/common/upload',
		  filePath: filePath,
		  name: 'file',
		 formData: {
		   userId: '12345', // 示例额外参数，可根据需要修改
		 },
		  header: header,
		  success: (uploadFileRes) => {
		   // console.log('上传成功:', uploadFileRes);
		   const data = JSON.parse(uploadFileRes.data);
		   // console.log('上传成功:', data);
		   if (data.code==1) {
		     uni.showToast({
		       title: $t('uploadsucess'),
		       icon: 'none',
		     });
		   	 realInfo.value[`${type}`] = data.data.url
		   } else {
		     uni.showToast({
		       // title: $t('uploadfail'),
		       title: data.msg,
		       icon: 'none',
		     });
		   }
		  },
		  fail: (err) => {
		    // console.log('上传失败:', err);
		    uni.showToast({
		      title: $t('uploadfail'),
		      icon: 'none',
		    });
		  },
		  complete() {
		    uni.hideLoading();
		  }
		});
		// 监听上传进度
		uploadTask.onProgressUpdate((res) => {
		// 更新 loading 提示的标题，显示当前进度
			uni.showLoading({
			  title: `上传中... ${res.progress}%`
			});
			if(res.progress==100){
				uni.hideLoading();
			}
			// console.log('当前上传进度：' + res.progress + '%');
		});
	}
	const realRule = ref(null)
	const popup2 = ref(null)
	const submitForm = () =>{
		realRule.value.validate(valid => {
			if (!valid) {
				// uni.showToast({
				// 	title: '提交中',
				// 	icon: 'none'
				// });
				const params = {
					real_name:realInfo.value.name,
					real_idcard:realInfo.value.idcrad,
					nation:realInfo.value.nationality,
					real_z_image:realInfo.value.brankImg,
					real_f_image:realInfo.value.afterImg
				}
				userRealAttest(params).then(res =>{
					// console.log('提交实名认证',res);
					if(res.code == 1){
						popup2.value.open()
						status.value = 0
						uni.setStorageSync('ISREALID', 0)
					}else{
						uni.showToast({
							title:res.msg,
							icon:'none',
							duration:3600
						})
					}
				})
				// popup2.value.open();
			}
		});
	}
	const dialogConfirm = () =>{
		popup2.value.close()
	}
	const backPage = () =>{
		// 返回上一页
		// uni.navigateBack({
		//   delta: 1 // 默认值为1，表示返回上一页
		// });
		history.back()
	}
	const status = ref(null)
	onMounted(() =>{
		status.value = Number(uni.getStorageSync('ISREALID'))
	})
</script>

<style scoped>
.u-input {
    border-radius: 12px!important;
    background-color: var(--theme-box-bg)!important;
    padding: 15px 20px!important;
	font-size: 15px !important;
}
::v-deep uni-button:after{
	border: none!important;
}
.idcard-item {
    width: 166px;
    border-radius: 12px;
    background-color: var(--theme-box-bg);
    padding: 12px;
    display: flex;
    flex-direction: column;
    align-items: center;
	box-sizing: border-box;
}
.idcard-item image{
	width: 142px;
	height: 88px;
}
.buyInfo{
	width: 260px;
	min-height: 100px;
	background-color: var(--theme-box-bg);
	border-radius: 12px;
	box-sizing: border-box;
}
.btn-group {
	display: flex;
	flex-direction: row;
	border-top-color: #f5f5f5;
	border-top-style: solid;
	border-top-width: 1px;
	margin-top: 20px;
}
.btn-b {
	display: flex;
	flex: 1;
	flex-direction: row;
	justify-content: center;
	align-items: center;
	height: 45px;
}
</style>
